import React, { useState, useRef, useEffect } from 'react';
import { Button, FormInstance } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getCommentsList, updateComments, batchUpdateComments } from '@/services/shop/api';
import { MsgType, showMsg, formatDate, isExits, isSupportSticky } from '@/utils/utils';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import Auditing from '@/components/Auditing';

const Index: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const auditingRef = useRef();
  const [ids, setIds] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const columns: ProColumns<SHOPAPI.ShopEvaluate>[] = [
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      hideInTable: true,
      fieldProps: {
        placeholder: '输入商品名称',
      }
    },
    {
      title: '用户账号',
      dataIndex: 'user_name',
      width: 150,
      fieldProps: {
        placeholder: '输入用户账号',
      }
    },
    {
      title: '评价星级',
      dataIndex: 'star',
      search: false,
      width: 90
    },
    {
      title: '评价详情',
      dataIndex: 'comment_content',
      width: 250,
      className: 'wordbreak',
      search: false
    },
    {
      title: '评价提交日期',
      dataIndex: 'create_date',
      hideInTable: true,
      valueType: 'date',
      render: (dom, entity) => {
        return entity.create_date + ' ' + entity.create_time;
      }
    },
    {
      title: '审核状态',
      dataIndex: 'status',
      width: 90,
      valueType: 'select',
      valueEnum: {
        U: '待审核',
        S: '审核通过',
        F: '审核拒绝'
      }
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      search: false,
      className: 'wordbreak',
      width: 150
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      search: false,
      className: 'wordbreak',
      width: 200
    },
    {
      title: '规格',
      dataIndex: 'specs_desc',
      search: false,
      className: 'wordbreak',
      width: 150
    },
    {
      title: '审核人',
      dataIndex: 'deal_name',
      search: false,
      width: 100
    },
    {
      title: '审核人工号',
      dataIndex: 'deal_id',
      search: false,
      width: 100
    },
    {
      title: '审核时间',
      dataIndex: 'deal_time',
      search: false,
      width: 180
    },
    {
      title: '操作',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      align: 'center',
      width: 100,
      valueType: 'option',
      render: (_, record) => {
        const { status } = record
        if (status === 'S' || status === 'F') {
          return []
        }

        return [
          <PermissionControl key="agree" action_id="600610002">
            <Auditing
              ref={auditingRef}
              loading={loading}
              module='C'
              onLoading={e => setLoading(e)}
              onError={() => {
                setLoading(false);
              }}
              onClick={() => {
                const data = Object.assign({}, { comment_id: record.comment_id, status: 'S', Action_Id: '600610002' });
                setLoading(true);
                auditingRef?.current?.onSign({sign_no: record.comment_id, sign_string: JSON.stringify(data), title: `小程序评价审批`}, async() => {
                  await updateComments(data).then(res => {
                    setLoading(false);
                    showMsg('已审核通过', MsgType.SUCCESS);
                    actionRef.current?.reload();
                  }).catch((error) => {
                    setLoading(false);
                    showMsg(error?.data?.errmsg);
                  });
                });
              }}
              _html={<a>通过</a>}
            />
          </PermissionControl>,
          <PermissionControl key="reject" action_id="600610003">
            <Auditing
              ref={auditingRef}
              loading={loading}
              module='C'
              onLoading={e => setLoading(e)}
              onError={() => {
                setLoading(false);
              }}
              onClick={() => {
                const data = Object.assign({}, { comment_id: record.comment_id, status: 'F', Action_Id: '600610003' });
                setLoading(true);
                auditingRef?.current?.onSign({sign_no: record.comment_id, sign_string: JSON.stringify(data), title: `小程序评价审批`}, async() => {
                  await updateComments(data).then(res => {
                    setLoading(false);
                    showMsg('已审核拒绝', MsgType.SUCCESS);
                    actionRef.current?.reload();
                  }).catch((error) => {
                    setLoading(false);
                    showMsg(error?.data?.errmsg);
                  });
                });
              }}
              _html={<a>拒绝</a>}
            />
          </PermissionControl>
        ]
      }
    }
  ];

  /**
   * 批量通过
   * @param ids 
   */
  const handleBatchAgree = async (ids: string[]) => {
    try {
      await batchUpdateComments({
        comment_ids: ids,
        status: 'S',
        Action_Id: '600610004'
      })
      showMsg('已通过审核', MsgType.SUCCESS);
      setIds([]);
      actionRef.current?.clearSelected?.();
      actionRef.current?.reload();
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  };

  /**
   * 批量拒绝
   * @param ids 
   */
  const handleBatchReject = async (ids: string[]) => {
    try {
      await batchUpdateComments({
        comment_ids: ids,
        status: 'F',
        Action_Id: '600610005'
      })
      showMsg('已审核拒绝', MsgType.SUCCESS);
      setIds([]);
      actionRef.current?.clearSelected?.();
      actionRef.current?.reload();
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  const onRowChange = (selectedRowKeys: React.Key[], selectedRows: SHOPAPI.ShopEvaluate[]) => {
    if (!selectedRows.length) {
      setIds([]);
      return
    }
    const rows = selectedRows.map(item => {
      return item.comment_id;
    });
    
    setIds(rows);
  }

  useEffect(() => {
    formRef.current?.setFieldsValue({
      status: 'U'
    });
    formRef.current?.submit();
  }, [status])

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<SHOPAPI.ShopEvaluate, SHOPAPI.ShopEvaluate & COMMON.PageParams>
        actionRef={actionRef}
        formRef={formRef}
        manualRequest={true}
        bordered
        rowKey="comment_id"
        loading={loading}
        search={{
          span: 6,
          labelWidth: 100,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [<PermissionControl key="search" action_id="600610001">{dom}</PermissionControl>];
          }
        }}
        request={async (params) => {
          try {
            if (params.create_date) {
              params.create_date = formatDate(params.create_date, 'YYYYMMDD');
            }
            const data: SHOPAPI.ShopEvaluateList = await getCommentsList(params);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }}
        columns={columns}

        rowSelection={{
          columnWidth: 80,
          onChange: onRowChange,
          getCheckboxProps: (record) => {
            return {
              disabled: record.status !== 'U'
            }
          }
        }}

        options={false}

        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'add',
                label: isExits('600610004') && <Button 
                  disabled={ids.length === 0}
                  onClick={() => {
                    handleBatchAgree(ids);
                  }} 
                  type="primary">
                  批量通过
                </Button>
              },
              {
                key: 'batchreject',
                label: isExits('600610005') && <Button 
                  disabled={ids.length === 0}
                  onClick={() => {
                    handleBatchReject(ids);
                  }} 
                  type="primary">
                  批量拒绝
                </Button>
              }
            ]
          }
        }}

        pagination={{
          showQuickJumper: true
        }}
        scroll={{
          x: 1200
        }}
      />
    </PageContainer>
  );
};

export default Index;
